package top.hkyzf.study.leetcode.string;

import org.junit.Test;

/**
 * @author 朱峰
 * @date 2022-3-1 8:39
 */
public class Z字形变换_6 {
    public String convert(String s, int numRows) {
        if (numRows == 1) {
            return s;
        }
        int length = s.length();
        // 每个周期多少字符
        int cycle = numRows + (numRows - 2);
        // 每个周期几列
        int cycleCol = numRows - 1;
        // 不满一个周期的字符占几列
        int surplus = length % cycle < numRows ? 1 : length % cycle + 1;
        int col = (length / (cycle)) * cycleCol + surplus;
        int[][] result = new int[numRows][col];
        result[0][0] = s.charAt(0);
        int[][] direct = {{1, 0}, {-1, 1}};
        int dire = 1;
        int newX = 0, newY =0;
        for (int i = 1; i < length; i++) {
            if (dire == 1) {
                newX = newX + direct[0][0];
                newY = newY + direct[0][1];
            } else {
                newX = newX + direct[1][0];
                newY = newY + direct[1][1];
            }
            result[newX][newY] = s.charAt(i);
            // 换方向
            if (i % (cycle / 2) == 0) {
                dire = -dire;
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j < col; j++) {
                if (result[i][j] != 0) {
                    sb.append((char) result[i][j]);
                }
            }
        }
        return sb.toString();
    }

    @Test
    public void testConvert () {
        String s = "PAYPALISHIRING";
        int numRows = 4;
        System.out.println(convert(s, numRows));
    }
}
